const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const { verToken } = require('./utils/token')

mongoose.connect('mongodb://localhost:27017/v1cake', {useNewUrlParser: true, useUnifiedTopology: true})

// 路由中间件
const UserRouter = require('./router/User')
const Userlogin = require('./router/Userlogin')
const UserAddress = require('./router/Address')
const UserFootPrint = require('./router/FootPrint')
const UserCollection = require('./router/UserCollection')
const Cart = require('./router/Cart')
const Apply = require('./router/Apply')
const Coustomer = require('./router/Coustomer')

const app = express()

app.use(cors())
// 处理请求主体数据
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.use('/api/v1cake/login', Userlogin)
app.use('/api/v1cake/user',(req, res, next) => {
  const {token} = req.headers
  verToken(token)
    .then(() => {
      next()
    })
    .catch(err => {
      res.json({
        code:400,
        msg: 'token校验出错',
        data: {
          err
        }
      })
    })
} ,UserRouter)

app.use('/api/v1cake/address', (req, res, next) => {
  const {token} = req.headers
  verToken(token)
    .then(() => {
      next()
    })
    .catch(err => {
      res.json({
        code:400,
        msg: 'token校验出错',
        data: {
          err
        }
      })
    })
} ,UserAddress)

app.use('/api/v1cake/footprint', (req, res, next) => {
  const {token} = req.headers
  verToken(token)
    .then(() => {
      next()
    })
    .catch(err => {
      res.json({
        code:400,
        msg: 'token校验出错',
        data: {
          err
        }
      })
    })
} ,UserFootPrint)

app.use('/api/v1cake/collection', (req, res, next) => {
  const {token} = req.headers
  verToken(token)
    .then(() => {
      next()
    })
    .catch(err => {
      res.json({
        code:400,
        msg: 'token校验出错',
        data: {
          err
        }
      })
    })
} ,UserCollection)

app.use('/api/v1cake/cart', (req, res, next) => {
  const {token} = req.headers
  verToken(token)
    .then(() => {
      next()
    })
    .catch(err => {
      res.json({
        code:400,
        msg: 'token校验出错',
        data: {
          err
        }
      })
    })
} ,Cart)

app.use('/api/v1cake/apply', (req, res, next) => {
  const {token} = req.headers
  verToken(token)
    .then(() => {
      next()
    })
    .catch(err => {
      res.json({
        code:400,
        msg: 'token校验出错',
        data: {
          err
        }
      })
    })
} ,Apply)

app.use('/api/v1cake/coustomer', (req, res, next) => {
  const {token} = req.headers
  verToken(token)
    .then(() => {
      next()
    })
    .catch(err => {
      res.json({
        code:400,
        msg: 'token校验出错',
        data: {
          err
        }
      })
    })
} ,Coustomer)

app.listen(8080, () => {
  console.log('serve is running at 8080')
})